//
//  WMEAudioManager.m
//  WMEMusic
//
//  Created by 恩叔 on 16/4/11.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "WMEAudioManager.h"
static WMEAudioManager *_instance = nil;
@interface WMEAudioManager ()
@property (nonatomic, strong)AVPlayer *avPlayer;
@property (nonatomic , strong)NSTimer *timer;

@end

@implementation WMEAudioManager

+(instancetype)defaultManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
//重写 init 方法
- (instancetype)init{
    if (self = [super init]) {
        _index = -1;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

- (void)playToEnd
{
    //确保 block 存在
    if (self.playToEndBlock) {
        //回调block
        self.playToEndBlock();
    }
}


//懒加载 创建AVplayer
- (AVPlayer *)avPlayer
{
    if (!_avPlayer) {
        _avPlayer = [[AVPlayer alloc] init];
        //读取存储的音量
        NSNumber *volumeNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"Volume"];
        if (volumeNumber) {
            _avPlayer.volume = volumeNumber.floatValue;
        }else {
            //未读取到 设置为1.0
            _avPlayer.volume = 1.0f;
        }
        _isPlay = NO;
    }
    return _avPlayer;
}
- (void)playingWithURL:(NSURL *)URL
{
    if (URL == nil && URL.absoluteString.length == 0) {
        return ;
    }
    if (self.avPlayer.currentItem) {
        //移除已有监听
        [self.avPlayer.currentItem removeObserver:self forKeyPath:@"status"];
    }
//    NSString *str4 = [URL substringWithRange:NSMakeRange(43, 8)];
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:str4]) {
        //        _avPlayer = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:[[NSUserDefaults standardUserDefaults] objectForKey:str4]]];
//    创建碟片
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:URL];
    //监听碟片
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    //放在音乐播放器中
    [self.avPlayer replaceCurrentItemWithPlayerItem:item];

//    }else{
//    //1.创建管理者对象
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    //2.确定请求的URL地址
//    NSURL *url = [NSURL URLWithString:URL];
//    
//    //3.创建请求对象
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    
//    //下载任务
//    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        //打印下下载进度
//        NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
//        
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        //下载地址
//        NSLog(@"默认下载地址:%@",targetPath);
//        
//        //设置下载路径，通过沙盒获取缓存地址，最后返回NSURL对象
//        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
//        NSLog(@"%@", filePath);
//        return [NSURL URLWithString:filePath];
//        
//        
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        //下载完成调用的方法
//        [[NSUserDefaults standardUserDefaults] setObject:[filePath path] forKey:str4];
//        //创建碟片
//        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:URL]];
//        //监听碟片
//        [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
//        //放在音乐播放器中
//        [self.avPlayer replaceCurrentItemWithPlayerItem:item];
//
//        NSLog(@"下载完成：");
//        NSLog(@"%@--%@",response,filePath);
//        
//    }];
//    
//    //开始启动任务
//    [task resume];
//    }
//    
//    [item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)play
{
    [_avPlayer play];
    self.isPlay = YES;
    //每 0.1 秒调用方法
    //安全判断
    if (!self.timer){
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playTimer) userInfo:nil repeats:YES];
        
        //将定时器加入 runloop 中
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        [self.timer fire];
    }
}
- (void)pause
{
    if (self.isPlay == YES) {
        [self.avPlayer pause];
        self.isPlay = NO;
        
        //销毁定时器
        if(self.timer){
            [self.timer invalidate];
            self.timer = nil;
        }
    }
}

- (void)playTimer
{
    //计算当前播放了多少秒
    CGFloat timer = _avPlayer.currentTime.value / _avPlayer.currentTime.timescale;
    
    if (self.playTimerBlock){
        self.playTimerBlock(timer);
    }
}

//从某一时刻开始播放
- (void)seekToTimer:(CGFloat)timer{
    
    //封装优化
    //先暂停
    [self pause];
    
    //CMTimeMakeWithSeconds(timer, self.avPlayer.currentTime.timescale)  某一时间 播放的进度
    
    //计算时间 timer * _sumTime
    [self.avPlayer seekToTime:CMTimeMakeWithSeconds(timer * _sumTime, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if(finished){
            [self play];
        }
    }];
}


//实现监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    //监听传值,获取改变后的值
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"未知情况");
            break;
        case AVPlayerItemStatusReadyToPlay:
//            if ([object isKindOfClass:[AVPlayerItem class]]) {
//                if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
//                    NSArray * array = self.avPlayer.currentItem.loadedTimeRanges;
//                    CMTimeRange timeRange = [array.firstObject CMTimeRangeValue]; //本次缓冲的时间范围
//                    NSTimeInterval totalBuffer = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //缓冲总长度
//                    NSLog(@"共缓冲%.2f",totalBuffer);
//                }
//            }
            //总播放的长度 除以 每一帧时间
            _sumTime = self.avPlayer.currentItem.duration.value / self.avPlayer.currentItem.duration.timescale;
            
            //播放
            [self play];
            NSLog(@"准备播放");
            break;
        case AVPlayerItemStatusFailed:
            NSLog(@"错误");
            break;
        default:{
            NSLog(@"其他情况");
        }
            break;
    }
    
}

//重写 setVolume
- (void)setVolume:(CGFloat)volume{
    _avPlayer.volume = volume;
}

//重写 volume

- (CGFloat)volume{
    return _avPlayer.volume;
}

@end
